package com.shunda.ysdgj.manager.controller;

import cn.hutool.core.text.UnicodeUtil;
import com.alibaba.fastjson.JSON;
import com.shunda.ysdgj.manager.service.AreaService;
import com.shunda.ysdgj.manager.service.goods.GoodsBrandCategoryService;
import com.shunda.ysdgj.manager.service.goods.GoodsSpecService;
import com.shunda.ysdgj.manager.service.system.SysRoleService;
import com.shunda.ysdgj.model.dto.goods.GoodsBrandCategoryFindDto;
import com.shunda.ysdgj.model.entity.Area;
import com.shunda.ysdgj.model.entity.goods.GoodsSpec;
import com.shunda.ysdgj.model.vo.ResultVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Tag(name = "测试接口")
@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
public class TestController {

    private final SysRoleService sysRoleService;
    private final GoodsBrandCategoryService goodsBrandCategoryService;
    private final GoodsSpecService goodsSpecService;
    private final AreaService areaService;

    @Operation(summary = "测试")
    @GetMapping("index")
    public ResultVo index() {
        return ResultVo.success(goodsBrandCategoryService.findByBrandId(1L));
    }

    @GetMapping("export")
    public void export(HttpServletResponse response) {
        sysRoleService.exportToExcel(response);
    }

    @PostMapping("importFromExcel")
    public void importFromExcel(MultipartFile file) {
        sysRoleService.importFromExcel(file);
    }

    @Operation(summary = "分页获取品牌分类列表")
    @PostMapping("goodsBrandCategroy")
    public ResultVo goodsBrandCategroy(@RequestBody GoodsBrandCategoryFindDto goodsBrandCategoryFindDto) {
        return ResultVo.success(goodsBrandCategoryService.findByPage(goodsBrandCategoryFindDto));
    }

    @Operation(summary = "添加商品规格")
    @PostMapping("addSpec")
    public ResultVo addSpec(@RequestBody GoodsSpec goodsSpec) {
        System.out.println(goodsSpec);
        if (!goodsSpecService.add(goodsSpec)) {
            return ResultVo.fail();
        }
        return ResultVo.success();
    }

    @GetMapping("areaCity")
    public ResultVo areaCity() {
        String fileName = "E:\\Document\\city.txt";
        List<Area> areaList = new ArrayList<>();
        try {
            String s = Files.readString(Paths.get(fileName));
            Map map = JSON.parseObject(s, Map.class);
            map.forEach((key, value) -> {
                String[] areaArr = value.toString().split(",");
                for (String areaStr : areaArr) {
                    String[] cityArr = areaStr.split("\\|");
                    Area area = new Area();
                    area.setId(Integer.valueOf(cityArr[1]));
                    area.setAreaLevel(2);
                    area.setParentId((Integer) key);
                    area.setAreaName(cityArr[0]);
                    areaList.add(area);
                }
            });
            return ResultVo.success(areaService.saveBatch(areaList));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("areaCounty")
    @Transactional
    public ResultVo areaCounty() {
        try {
            List<Area> cityList = areaService.lambdaQuery().eq(Area::getAreaLevel, 2).list();
            for (Area city : cityList) {
                String urlStr = String.format("https://fts.jd.com/area/get?fid=%s", city.getId());
                URL url = new URI(urlStr).toURL();
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                reader.close();
                String response = UnicodeUtil.toString(stringBuilder.toString());
                if (!response.isEmpty()) {
                    List<Map<String, Object>> countyList = JSON.parseObject(response, List.class);
                    if (countyList != null && !countyList.isEmpty()) {
                        List<Area> areaList = new ArrayList<>();
                        for (Map<String, Object> county : countyList) {
                            Area area = new Area();
                            area.setId((Integer) county.get("id"));
                            area.setParentId(city.getId());
                            area.setAreaName((String) county.get("name"));
                            area.setAreaLevel(3);
                            areaList.add(area);
                        }
                        areaService.saveBatch(areaList);
                    }
                }
            }
            return ResultVo.success();
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("areaVillage")
    @Transactional
    public ResultVo areaVillage() {
        try {
            List<Area> cityList = areaService.lambdaQuery().eq(Area::getAreaLevel, 3).list();
            for (Area city : cityList) {
                String urlStr = String.format("https://fts.jd.com/area/get?fid=%s", city.getId());
                URL url = new URI(urlStr).toURL();
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                reader.close();
                String response = UnicodeUtil.toString(stringBuilder.toString());
                if (response != null && !response.isEmpty()) {
                    List<Map<String, Object>> countyList = JSON.parseObject(response, List.class);
                    if (countyList != null && !countyList.isEmpty()) {
                        List<Area> areaList = new ArrayList<>();
                        for (Map<String, Object> county : countyList) {
                            Area area = new Area();
                            area.setId((Integer) county.get("id"));
                            area.setParentId(city.getId());
                            area.setAreaName((String) county.get("name"));
                            area.setAreaLevel(4);
                            areaList.add(area);
                        }
                        areaService.saveBatch(areaList);
                    }
                }
            }
            return ResultVo.success();
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
    }

}
